import 'package:bindings_compatible/bindings_compatible.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/utils/platform.dart';
import 'package:kq_flutter_core_widget/config/kq_core_global.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_widgets/config/kq_global.dart';
import 'package:kq_flutter_widgets/widgets/searchBar/kq_search_bar.dart';

import '../../resources/kq_theme_colors.dart';
import '../../resources/images.dart';
import '../../theme/kq_theme_manager.dart';
import '../button/kq_head_button.dart';
import '../dropDownMenu/kq_drop_down_menu.dart';

/// 通用AppBar
/// K6 搬过来的
class KqHeadBar extends KqAppBar {
  /// KqHeadBar--标题
  final String? headTitle;

  /// 背景颜色
  final Color? bgColor;

  /// 是否显示下拉图标
  final bool showDropIcon;

  /// 标题点击回调
  final VoidCallback? onTapTitle;

  /// 标题下拉菜单数据菜单列表
  final List<KqDropMenuData>? dropMenuData;

  /// 下拉菜单控制器
  final KqDropDownMenuController? menuController;

  /// 标题下拉菜单选中回调，返回true，表示可以选中
  final Function(KqDropMenuData menuData)? onSelected;

  /// 字体颜色
  final Color color;

  /// Icon颜色
  final Color iconColor;

  /// 返回按钮的图标，自定义 [KqHeadButton] 里面的 [widget] 属性
  final Widget? backIcon;

  /// 返回提示文字
  final String? backTooltip;

  /// 是否展示左侧返回按钮
  final bool showBack;

  /// KqHeadBar--右侧自定义区域，如无特殊情况，请统一使用[KqHeadButton]
  @override
  final dynamic actions;

  /// 自定义返回事件
  final VoidCallback? back;

  /// 自定义标题控件
  final Widget? customTitle;

  /// 标题栏显示形态
  final TitleBarShowMode showMode;

  /// 自定义搜索框左边控件
  final Widget? customSearchLeftWidget;

  /// 自定义搜索框右边控件
  final Widget? customSearchRightWidget;

  /// 取消搜索回调
  final Function()? onCancelSearch;

  /// 数值变化监听
  final ValueChanged<String>? onSearchChanged;

  /// 搜索回调（包括扫码枪和软键盘的提交）
  final Function(String value, KqSearchBarState state)? onSearchSubmit;

  /// 用于监听停顿回调，基于onTextChange，500ms没有输入则回调，避免频繁调用接口。
  final Function(String str)? onSearchMonitor;

  /// 清空按钮点击监听
  final VoidCallback? onSearchCleared;

  /// 搜索hint
  final String? placeHolder;

  /// 搜索输入框TextEditingController
  final TextEditingController? editingController;

  /// 搜索取消按钮提示文字
  final String? cancelBtnTooltip;

  const KqHeadBar({
    super.key,
    this.headTitle,
    this.actions,
    this.iconColor = const Color(0xffffffff),
    this.backIcon,
    this.back,
    this.bgColor,
    this.showDropIcon = false,
    this.dropMenuData,
    this.menuController,
    this.onSelected,
    this.onTapTitle,
    this.customTitle,
    this.placeHolder,
    this.editingController,
    this.color = const Color(0xffffffff),
    this.showBack = true,
    this.customSearchLeftWidget,
    this.customSearchRightWidget,
    this.onSearchChanged,
    this.onSearchSubmit,
    this.onSearchMonitor,
    this.onSearchCleared,
    this.backTooltip,
    this.cancelBtnTooltip,
    super.statusBarBrightness,
    super.statusBarIconBrightness,
    super.statusBarColor,
    super.primary,
    this.showMode = TitleBarShowMode.normal,
    this.onCancelSearch,
  })  : assert(
            actions == null || actions is Widget || (actions is List<Widget>)),
        super(title: headTitle, actions: actions);

  @override
  Widget build(BuildContext context) {
    return DefaultTextStyle(
      style: TextStyle(color: color),
      child: KqAppBar(
          // showDefaultBottom: true,
          //默认显示返回按钮
          backgroundColor:
              bgColor ?? KqThemeManager.getCommonConfig().mainColor,
          isSearchMode: showMode == TitleBarShowMode.search,
          title: showMode == TitleBarShowMode.normal
              ? customTitle ??
                  KqAppBarTitle(headTitle ?? '',
                      showDropIcon: showDropIcon,
                      onTapTitle: onTapTitle,
                      textStyle: TextStyle(
                        fontSize: 18.sp,
                        color: color,
                      ),
                      dropMenuData: dropMenuData,
                      onSelected: onSelected,
                      menuController: menuController)
              : KqSearchBar(
                  outerBgColor: KqThemeColors.bgTransparent,
                  innerBgColor: KqThemeColors.bgTransparent,
                  outHeight: KqAppBar.appBarHeight(),
                  searchIconColor: KqThemeColors.bgWhite,
                  cursorColor: KqThemeColors.bgWhite,
                  alwaysShowCancelBtn: true,
                  cancelTextColor: KqThemeColors.bgWhite,
                  textColor: KqThemeColors.bgWhite,
                  placeHolderTextColor: KqThemeColors.bgD,
                  hintText: placeHolder,
                  customLeftWidget: customSearchLeftWidget,
                  customRightWidget: customSearchRightWidget,
                  editController: editingController,
                  unFocusWhenCleared: false,
                  onChanged: onSearchChanged,
                  onSubmit: onSearchSubmit,
                  onCleared: onSearchCleared,
                  customLeftIcon: Icon(
                    Icons.search,
                    color: KqThemeColors.bgWhite,
                    size: 20.r,
                  ),
                  cancelBtnTooltip: cancelBtnTooltip,
                  onMonitor: onSearchMonitor,
                  autofocus: true,
                  onCancel: onCancelSearch,
                ),
          statusBarBrightness: statusBarBrightness,
          statusBarIconBrightness: statusBarIconBrightness,
          statusBarColor: statusBarColor,
          leading: showMode == TitleBarShowMode.normal && showBack
              ? KqHeadButton(
                  widget: backIcon ??
                      Icon(
                        Icons.arrow_back_ios,
                        size: 20.r,
                        color: iconColor,
                      ),
                  tooltip: backTooltip ?? '返回',
                  onTap: back ?? Get.back,
                )
              : null,
          primary: primary,
          actions: showMode == TitleBarShowMode.normal ? actions : null),
    );
  }

  /// 设置状态栏颜色
  ///
  /// [statusBarBrightness]及[statusBarIconBrightness]控制状态栏图标/文本颜色
  ///
  /// [statusBarColor]控制状态栏颜色
  static setStatusBarColor({
    Brightness? statusBarBrightness,
    Brightness? statusBarIconBrightness,
    Color? statusBarColor,
  }) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarBrightness: statusBarBrightness ?? Brightness.light,
      statusBarIconBrightness: statusBarIconBrightness ?? Brightness.light,
      statusBarColor: statusBarColor ?? Colors.transparent,
    ));
  }
}

enum TitleBarShowMode {
  /// 普通状态
  normal,

  /// 搜索状态
  search
}

class KqAppBar extends StatelessWidget implements PreferredSizeWidget {
  /// 导航栏左侧活动区域,在为null且
  final Widget? leading;

  /// AppBar标题,必须是String或者Widget类型
  /// 为String时,会使用[KqAppBarTitle]来加载title
  final dynamic title;

  /// 为了方便业务使用，可以设置为Widget或者List<Widget>
  /// 传入的Widget会自动添加边距并转化为List<Widget>
  /// 传入的List<Widget>会自动添加右边距和action之间的间距
  final dynamic actions;

  /// 以下属性都对应于[AppBar]中的属性
  /// 详细介绍可以查阅[AppBar]的文档
  final Color? backgroundColor;
  final double elevation;
  final double? leadingWidth;
  final Color? shadowColor;

  /// 要不要添加SafeArea
  final bool primary;
  final bool excludeHeaderSemantics;

  /// 状态栏亮暗
  final Brightness? statusBarBrightness;

  /// 状态栏图标/文本亮暗
  final Brightness? statusBarIconBrightness;

  /// 状态栏颜色
  final Color? statusBarColor;

  /// 默认处理了返回按钮，flutter的pop，如果是native打开的话，可能需要单独处理,否则会出现白屏
  /// backLeadCallback是默认的处理回调
  /// DefaultLeadingCallBack 也可以通过改方法参数 设置统一的返回处理，该参数是静态的
  final VoidCallback? backLeadCallback;

  /// 是否显示默认的eeeeee分割线，默认显示，可以设置为不显示
  final bool? showDefaultBottom;
  final bool showLeadingDivider;

  final bool isSearchMode;

  const KqAppBar(
      {super.key,
      this.leading,
      this.showLeadingDivider = false,
      this.title,
      this.actions,
      this.backgroundColor,
      this.elevation = 0,
      this.statusBarColor,
      this.backLeadCallback,
      this.showDefaultBottom,
      this.leadingWidth,
      this.statusBarBrightness,
      this.statusBarIconBrightness,
      this.shadowColor,
      this.isSearchMode = false,
      this.excludeHeaderSemantics = false,
      this.primary = true})
      : assert(
            actions == null || actions is Widget || (actions is List<Widget>)),
        assert(title == null || title is String || title is Widget);

  @override
  Size get preferredSize {
    return Size.fromHeight(appBarHeight());
  }

  @override
  Widget build(BuildContext context) {
    useWidgetsBinding().addPostFrameCallback((_) {
      KqHeadBar.setStatusBarColor(
          statusBarBrightness: statusBarBrightness,
          statusBarIconBrightness: statusBarIconBrightness,
          statusBarColor: statusBarColor);
    });

    var buildAppBarTitle = _buildAppBarTitle();

    var wrapActions = _wrapActions();

    var wrapLeading = _wrapLeading();

    var leadingSize = _culLeadingSize();

    var barHeight = appBarHeight();

    Widget child = SizedBox(
      height: barHeight,
      child: Stack(
        children: [
          Positioned(
              left: 0,
              right: 0,
              top: 0,
              bottom: 0,
              child: Row(
                children: [
                  if (wrapLeading != null) wrapLeading,
                  const Spacer(),
                  if (wrapActions != null) ...wrapActions,
                ],
              )),
          if (buildAppBarTitle != null)
            Positioned(
                left: isSearchMode ? 0 : leadingSize + 14.r,
                right: isSearchMode ? 0 : leadingSize + 14.r,
                top: 0,
                bottom: 0,
                child: Align(
                  alignment: Alignment.center,
                  child: buildAppBarTitle,
                )),
        ],
      ),
    );

    if (primary) {
      child = SafeArea(
        bottom: false,
        child: child,
      );
    }

    return Material(
      elevation: elevation,
      color: Colors.transparent,
      child: IconTheme(
        data: IconThemeData(color: KqThemeColors.bgWhite, size: 20.r),
        child: Container(
          width: double.infinity,
          color: backgroundColor ??
              KqThemeManager.getCommonConfig().mainColor ??
              KqThemeColors.bgBlue,
          child: child,
        ),
      ),
    );

    // return AppBar(
    //   key: key,
    //   leading: _wrapLeading(),
    //   leadingWidth: leadingWidth ?? _culLeadingSize(),
    //   titleSpacing: 0,
    //   automaticallyImplyLeading: false,
    //   title: _buildAppBarTitle(),
    //   centerTitle: true,
    //   elevation: elevation,
    //   backgroundColor: backgroundColor,
    //   actions: _wrapActions(),
    //   systemOverlayStyle: SystemUiOverlayStyle.light,
    //   scrolledUnderElevation: 0,
    //   shadowColor: shadowColor,
    //   primary: primary,
    //   excludeHeaderSemantics: excludeHeaderSemantics,
    // );
  }

  // 根据输入的leading 设置默认的leadingWidth
  double _culLeadingSize() {
    if (leadingWidth != null) {
      return leadingWidth!;
    }
    if (leading == null) {
      return 0;
    }
    return 14.r + 40.r;
  }

  static double appBarHeight() {
    bool isiPad = PlatformEx.isIOS &&
        MediaQuery.of(KqCoreGlobal.globalContext).size.shortestSide > 600;
    return KqThemeManager.getCommonConfig().titleBarHeight ??
        (isiPad ? 34.r : 44.r);
  }

  // 对[actions]进行包装: 单一的Widget会添加右边距
  //                     List<Widget>在添加右边距的 并 添加action中的间距
  List<Widget>? _wrapActions() {
    if (actions == null || !(actions is List<Widget> || actions is Widget)) {
      return null;
    }
    List<Widget> actionList = <Widget>[];

    if (actions is List<Widget>) {
      if (actions.isEmpty) {
        return actionList;
      }
      List<Widget> tmp = (actions as List<Widget>).map((_) {
        return _;
      }).toList();

      for (int i = 0, n = tmp.length; i < n; i++) {
        actionList.add(tmp[i]);
        if (i != n - 1) actionList.add(SizedBox(width: 8.r));
      }
    } else {
      Widget realAction = actions;
      actionList.add(realAction);
    }
    return actionList..add(SizedBox(width: 14.r));
  }

  // 详情请参考_ToolbarLayout的布局方法
  Widget? _buildAppBarTitle() {
    Widget? realTitle;
    if (title is Widget) {
      return title;
    }
    if (title is String) {
      realTitle = KqAppBarTitle(
        title,
      );
    }

    return realTitle;
  }

  //添加左边距
  Widget? _wrapLeading() {
    if (leading == null) {
      return null;
    }
    return Container(
      padding: EdgeInsets.only(left: 14.r),
      child: leading,
    );
  }
}

/// [KqAppBar.title]的默认实现
/// 标题文字个数限制在15个以内，并且单行展示
class KqAppBarTitle extends StatelessWidget {
  final String title;

  /// 是否显示下拉图标
  final bool showDropIcon;

  final VoidCallback? onTapTitle;

  final TextStyle? textStyle;

  final List<KqDropMenuData>? dropMenuData;

  final KqDropDownMenuController? menuController;

  /// 选中回调，返回true，表示可以选中
  final Function(KqDropMenuData menuData)? onSelected;

  const KqAppBarTitle(this.title,
      {Key? key,
      this.textStyle,
      this.showDropIcon = false,
      this.onTapTitle,
      this.onSelected,
      this.menuController,
      this.dropMenuData})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    Widget titleWidget = !showDropIcon
        ? ConstrainedBox(
            constraints: BoxConstraints.loose(
                Size.fromWidth((textStyle?.fontSize ?? 18.sp) * (15 + 1))),
            child: Container(
              height: KqAppBar.appBarHeight(),
              alignment: Alignment.center,
              child: Text(
                title,
                textAlign: TextAlign.center,
                style: textStyle ??
                    TextStyle(fontSize: 18.sp, fontWeight: FontWeight.normal),
                overflow: TextOverflow.ellipsis,
              ),
            ),
          )
        : ConstrainedBox(
            constraints: BoxConstraints.loose(
                Size.fromWidth((textStyle?.fontSize ?? 18.sp) * (15 + 1))),
            child: Container(
              height: KqAppBar.appBarHeight(),
              alignment: Alignment.center,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  ConstrainedBox(
                    constraints: BoxConstraints(
                        maxWidth: (textStyle?.fontSize ?? 18.sp) *
                            ((showDropIcon ? 12 : 15) + 1)),
                    child: Text(
                      title,
                      // '测试很长的数据测试很长的数据测试很长的数据',
                      textAlign: TextAlign.center,
                      style: textStyle ??
                          TextStyle(
                              fontSize: 18.sp, fontWeight: FontWeight.normal),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  if (showDropIcon)
                    SizedBox(
                      width: 4.r,
                    ),
                  if (showDropIcon)
                    Image.asset(
                      Images.commonIcJiantouDown16White,
                      width: 16.r,
                      height: 16.r,
                      fit: BoxFit.fill,
                      package: KqGlobal.packageName,
                    ),
                ],
              ),
            ),
          );
    if (!showDropIcon) {
      if (onTapTitle == null) {
        return titleWidget;
      } else {
        return KqInkWell(
          onTap: () {
            onTapTitle?.call();
          },
          enableRipple: false,
          child: titleWidget,
        );
      }
    } else {
      return KqDropDownMenu(
        menuController: menuController ?? KqDropDownMenuController(),
        maxQty: 6,
        menuData: dropMenuData!,
        onSelected: (menuData) {
          onSelected?.call(menuData);
        },
        child: KqInkWell(
          onTap: () {
            onTapTitle?.call();
          },
          enableRipple: false,
          child: titleWidget,
        ),
      );
    }
  }
}
